package worldwind.kml.tree;

import worldwind.kml.model.KMLPlacemark;
import worldwind.kml.model.KMLFolder;
import worldwind.kml.model.KMLObject;

import javax.swing.*;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import gov.nasa.worldwind.WorldWindow;

/**
 * A JTree for displaying the KML document.  It handles check marks here, even though
 * that should probably be done somewhere else.
 */
public class KMLTreeView extends JTree {

    WorldWindow wwd;

    public KMLTreeView(WorldWindow wwd, TreeModel newModel) {
        super(newModel);

        this.wwd = wwd;

        setCellRenderer(new CheckboxTreeCellRenderer());

        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                TreePath path = getPathForLocation(e.getX(), e.getY());
                if(path==null)
                    return;
                if(e.getX()>getPathBounds(path).x+32)
                    return;

                Object obj = path.getLastPathComponent();

                if (obj instanceof KMLPlacemarkTreeNode) {
                    togglePlacemark(((KMLPlacemarkTreeNode)obj).getPlacemark());
                } else if (obj instanceof KMLFolderTreeNode) {
                    toggleFolder(((KMLFolderTreeNode)obj).getFolder());
                }

                Object docObj = path.getPathComponent(1);
                if (docObj instanceof KMLDocTreeNode) {
                    ((KMLDocTreeNode)docObj).getLayer().setInvalid(true);
                }

                repaint();
                KMLTreeView.this.wwd.redraw();
            }
        });
    }

    private void togglePlacemark(KMLPlacemark placemark) {
        placemark.setVisible(!placemark.isVisible());
    }

    private void toggleFolder(KMLFolder folder) {
        if (folder.isVisible()) {
            setChildrenVisibility(folder, false);
        } else {
            setChildrenVisibility(folder, true);
        }
        folder.setVisible(!folder.isVisible());
    }

    private void setChildrenVisibility (KMLFolder folder, boolean visible) {
        for (KMLFolder childFolder : folder.getChildFolders()) {
            childFolder.setVisible(visible);
        }
        for (KMLObject obj : folder.getObjects()) {
            if (obj instanceof KMLPlacemark) {
                ((KMLPlacemark)obj).setVisible(visible);
            }
        }
    }
}




